<?php
namespace App\Core\Redis;

use Exception;
use Redis;

class Db
{
    //连接数组
    public static array $connectArr = [];

    /**
     * 获取redis连接
     * @param string $key
     * @return Redis
     * @throws Exception
     */
    public static function getRedis(string $key = 'redis')
    {
        if(!isset(static::$connectArr[$key])){
            static::$connectArr[$key] = static::connect($key);
            return static::$connectArr[$key];
        }
        try{
            if(!static::$connectArr[$key]->ping()){
                static::$connectArr[$key]->close();
                static::$connectArr[$key] = null;
                unset(static::$connectArr[$key]);
                return static::getRedis($key);
            }
            return static::$connectArr[$key];
        }catch (\Throwable $e){
            static::$connectArr[$key]->close();
            static::$connectArr[$key] = null;
            unset(static::$connectArr[$key]);
            return static::getRedis($key);
        }
    }

    /**
     * @param string $key
     * @return Redis
     * @throws Exception
     */
    public static function connect(string $key = 'redis')
    {
        $config = config();
        if(!isset($config[$key])){
            throw new Exception('redis配置错误('.$key.'未配置)');
        }
        $dbConfig = $config[$key];
        if(empty($dbConfig['hostname'])){
            throw new Exception('redis配置错误(hostname未配置)');
        }
        if(empty($dbConfig['port'])){
            throw new Exception('redis配置错误(port未配置)');
        }
        if(!isset($dbConfig['database'])){
            throw new Exception('redis配置错误(database未配置)');
        }
        $redis = new Redis();
        $redis->connect($dbConfig['hostname'],$dbConfig['port']);
        if(!empty($dbConfig['password'])){
            if(!$redis->auth($dbConfig['password'])){
                throw new Exception('redis配置错误(password错误)');
            }
        }
        $redis->select($dbConfig['database']);
        return $redis;
    }
}